<template>
  <div>
    <el-radio-group v-model="logType" style="margin-bottom: 10px;" size="small">
      <el-radio-button label="1">日报</el-radio-button>
      <el-radio-button label="2">周报</el-radio-button>
      <!-- <el-radio-button label="3">半月报</el-radio-button> -->
      <el-radio-button label="4">月报</el-radio-button>
    </el-radio-group>
    <div v-if="logType==1">
      <div>
        <div style="padding: 20px 5px;">
          <div v-for="item in logs" style="margin-bottom:25px">
            <div style="margin-bottom: 5px;" @click="toggleLogEditor(item)">
              <el-button v-if="item.hideEditor" icon="el-icon-plus" type="text" circle size="mini" ></el-button>
              <el-button v-if="!item.hideEditor" icon="el-icon-minus" type="text" circle size="mini"></el-button>
              项目： {{item.projectName}}
            </div>
            <div v-if="!item.hideEditor">
              <rich-editor :members="members" :disabled="editable==0" :rows="3" :data="item" contentKey="logContent" avatarsKey="atDingIds" @change="tmpSave()"></rich-editor>
              <uploador style="margin-top: 5px;" :files.sync="item.attachmentList"></uploador>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="phased" v-if="logType>1">
      <div class="item">
        <div class="must">工作内容：</div>
        <rich-editor :members="members" :rows="3" :data="getPhasedLog()[0]" contentKey="logContent1" avatarsKey="atDingIds"></rich-editor>
      </div>
      <div class="item">
        <div class="must">主要成效：</div>
        <rich-editor :members="members" :rows="3" :data="getPhasedLog()[0]" contentKey="logContent2" avatarsKey="atDingIds"></rich-editor>
      </div>
      <div class="item">
        <div class="must">下期计划：</div>
        <rich-editor :members="members" :rows="3" :data="getPhasedLog()[0]" contentKey="logContent3" avatarsKey="atDingIds"></rich-editor>
      </div>
      <uploador :files.sync="getPhasedLog()[0].attachmentList"></uploador>
    </div>
    <div>
      <div style="margin-bottom: 5px">抄送人</div>
      <avatar-list :disabled="editable==0" ref="listcc" :maxNumber="20" ></avatar-list>
    </div>
    <el-button size="mini" style="position: fixed; top: 60px; right:15px;" type="info" @click="getLogs()" >刷新</el-button>
    <div style="padding-top: 10px">
      <span style="color:#F56C6C">{{errorMsg}}</span>
      <el-button v-if="editable==1" size="mini" style="float:right" type="primary" @click="writeLog()" :loading="loading">提交</el-button>
      <el-button v-if="editable==0" size="mini" style="float:right" type="primary" @click="editable=true">修改</el-button>
    </div>
  </div>
</template>

<script>
  import 'element-ui/lib/theme-chalk/index.css';
  import dingMixin from  '@/mixins/ding'
  import AvatarList from '@/components/ding/avatar-list'
  import RichEditor from '@/components/ding/rich-editor'
  import Uploador from  '@/components/common/uploador'

  export default {
    data () {
      return {
        projectsQuery:{
          queryDepartmentId: 0,
          queryDepartmentName:''
        },
        logType:1,
        weekLog:{},
        monthLog:{},
        halfMonthLog:{},
        logs: [],
        errorMsg:'',
        globalCc: [],
        editable: 1,
        members: [],
        loading:false
      }
    },
    components:{
      AvatarList,RichEditor,Uploador
    },
    mixins: [dingMixin],
    created(){
      this.loadMembers().then(data=>this.members = data);
      this.load();
    },
    methods: {
      tmpSave(){
        localStorage.setItem('tempLog', JSON.stringify(this.logs));
      },
      getTmpLog(){
        let tmp = localStorage.getItem('tempLog')
        if(tmp>''){
          let tmpLogs = JSON.parse(tmp)
          for(let item of this.logs){
            let m = tmpLogs.filter(x=>x.projectId == item.projectId);
            console.log(m)
            if(m.length>0){
              item.logContent = m[0].logContent
            }
          }
        }
      },
      clearTmpLog(){
        localStorage.setItem('tempLog', '');
      },
      toggleLogEditor(item){
        item.hideEditor=!item.hideEditor
        this.$nextTick(
          ()=>{
            this.$forceUpdate()
          }
        )
      },
      load() {
        this.errorMsg = ''
        this.getLogs();
        this.getGlobalCc();
      },
      getSubmitLogs(){
        let ls = [];
        for(let item of this.logs){
          if(item.logContent>''){
            ls.push({projectId: item.projectId, memberId: this.userInfo.dingId, logContent: item.logContent, attachments: this.getAttachmentStr(item)});
          }
        }
        return ls;
      },
      getAttachmentStr(item){
        let res = []
        for(let i of item.attachmentList){
          let url = i.response==null?i.url:i.response.url
            res.push({name: i.name, url:  url})
        }
        return JSON.stringify(res);
      },
      getPhasedLog(){
        if(this.logType==2){
          this.weekLog.projectId = -2;
          this.weekLog.memberId = this.userInfo.dingId;
          if(!this.weekLog.attachmentList){
            //this.weekLog.attachments = ''
            this.weekLog.attachmentList = []
          }
          return [this.weekLog];
        }
        else if(this.logType==3){
          this.halfMonthLog.projectId = -3;
          this.halfMonthLog.memberId = this.userInfo.dingId;
          if(!this.halfMonthLog.attachmentList){
           // this.halfMonthLog.attachments = ''
            this.halfMonthLog.attachmentList = []
          }
          return [this.halfMonthLog];
        }
        else if(this.logType==4){
          this.monthLog.projectId = -4;
          this.monthLog.memberId = this.userInfo.dingId;
          if(!this.monthLog.attachmentList){
            //this.monthLog.attachments = ''
            this.monthLog.attachmentList = []
          }
          return [this.monthLog];
        }
      },
      writeLog(){
        this.loading = true
        let submitLogs = []
        if(this.logType == 1){
          submitLogs = this.getSubmitLogs();
        }
        else{
          submitLogs = this.getPhasedLog();
          if(!submitLogs[0].logContent1){
            this.errorMsg = '请填写工作内容'
            this.loading = false
            return;
          }
          if(!submitLogs[0].logContent2){
            this.errorMsg = '请填写主要成效'
            this.loading = false
            return;
          }
          if(!submitLogs[0].logContent3){
            this.errorMsg = '请填写下期计划'
            this.loading = false
            return;
          }
          console.log(submitLogs)
          submitLogs[0].attachments =this.getAttachmentStr(submitLogs[0]);
          submitLogs[0].logContent = '工作内容：'+ submitLogs[0].logContent1 + '\n主要成效：' +submitLogs[0].logContent2 + '\n下期计划：' + submitLogs[0].logContent3
        }

        let cc = this.$refs.listcc.getDingEmpIds();
        if(submitLogs.length==0){
          this.errorMsg = '请填写项目日志内容'
          this.loading = false
          return;
        }
        this.errorMsg = ''
        this.$http({
          url: this.$http.adornUrl(`/wpb/projectlog/writeLogs`),
          method: 'post',
          data: this.$http.adornData({globalCc: cc,logs:submitLogs})
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({message: '操作成功', type: 'success',duration: 1000, offset:50})
            this.clearTmpLog()
            this.$emit('gotoRead');
          } else {
            this.$message({message: data.msg, type: 'error',duration: 1000, offset:50})
          }
        }).finally(()=>{
          this.loading = false
        })
      },
      getGlobalCc(){
        this.$http({
          url: this.$http.adornUrl('/wpb/projectlog/getGlobalCc'),
          method: 'post',
          data: this.$http.adornData({})
        }).then(({data}) => {
            if (data && data.code === 0) {
              this.globalCc = data.cc;
              this.$refs.listcc.bindData(this.globalCc);
            } else {
              this.$message({message: data.msg, type: 'error',duration: 1000, offset:50})
            }
          }
        ).catch(error=>{
          console.info(error)
        })
      },
      getLogs(){
        this.$http({
          url: this.$http.adornUrl('/wpb/projectlog/getLogsWithEmpty'),
          method: 'post',
          data: this.$http.adornData({
            'page': 1,
            'limit': 1000,
            'memberId': this.userInfo.dingId,
            'logBeginTime': new Date(),
            'logEndTime': new Date()
          })
        }).then(({data}) => {
            if (data && data.code === 0) {
              this.logs = data.data;
              this.getTmpLog()
              if(this.getSubmitLogs().length>0){
                this.editable = 1;
              }
              else{
                this.editable = 1;
              }
            } else {
              this.logs = []
            }
            this.logs.forEach(x=>x.hideEditor=true)
          }
        ).catch(error=>{
          console.info(error)
        })
      },
    }
  }
</script>
<style lang="scss" scoped>
  .phased{
    .item {
      padding: 20px 5px;
    }
  }

  .must:before{
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
  }

</style>
